package com.yinhai.asynctask;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

import com.yinhai.activity.CloudNoteSortActivity;
import com.yinhai.model.CloudNote;
import com.yinhai.service.CloudNoteServiceImpl;

public class FindCloudNoteTask  extends AsyncTaskForHttp{
	String retStr = null;
	public FindCloudNoteTask(Context context) {
		super(context);
	}
	
	public FindCloudNoteTask(Context context, boolean autoForword) {
		super(context, autoForword);
	}

	public FindCloudNoteTask(Context context, int timeoutRequestCount,
			boolean autoForword) {
		super(context, timeoutRequestCount, autoForword);
	}
	@Override
	protected void parse(Map<String, Object> result) {
		this.retStr = (String)result.get(AsyncTaskContext.RESPONSE_CONTENT);
		JSONObject jsonObject;
		try {
			jsonObject = new JSONObject(retStr);
			
			String flag = jsonObject.getString("flag");
			if(flag.equals("0")){
				Toast.makeText(context, "无需要恢复数据", Toast.LENGTH_SHORT).show();
			}else if(flag.equals("-1")){
				Toast.makeText(context, "恢复失败,请重试", Toast.LENGTH_SHORT).show();
			}else if(flag.equals("1")){
				CloudNoteServiceImpl cnServiceIpml = new CloudNoteServiceImpl(context);
				JSONArray jsonArray = jsonObject.getJSONArray("data");
				List<CloudNote> listCn = new ArrayList<CloudNote>();
				for(int i =0;i<jsonArray.length();i++){
					JSONObject obj = jsonArray.getJSONObject(i);
					CloudNote cNote = new CloudNote();
					cNote.setCreate_time(obj.getString("create_time"));
					cNote.setNote(obj.getString("note"));
					cNote.setPhone(obj.getString("phone"));
					cNote.setPid(obj.getString("pid"));
					cNote.setUuid(obj.getString("uuid"));
					listCn.add(cNote);
				}
				
				cnServiceIpml.delAllList();
				for(int i =0;i<listCn.size();i++){
					cnServiceIpml.insert(listCn.get(i));
				}
				Toast.makeText(context, "恢复数据成功", Toast.LENGTH_SHORT).show();
				Intent imgroupBroadcast = new Intent("com.cloudnote.update");
				imgroupBroadcast.putExtra("bc_uuid", "-2");
				imgroupBroadcast.putExtra("is_del", "0");
				context.sendBroadcast(imgroupBroadcast);
			}
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
